package com.boxedinsoftware.betamax.dial;



import de.ub0r.android.lib.apis.ContactsWrapper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
;


public class dialNow extends BetamaxCheckLicence  {
    /** Called when the activity is first created. */
	
	
		protected static final String[] PROVIDERS = {"none" , "12voip.com","actionvoip.com", "budgetsip.com",
	   "calleasy.com", "callingcredit.com" , "cheapvoip.com", "dialnow.com", "freecall.com", "internetcalls.com",
	   "intervoip.com", "jumblo.com", "justvoip.com", "lowratevoip.com", "netappel.fr", "nonoh.net",
	   "poivy.com", "powervoip.com", "rynga.com", "sipdiscount.com", "smartvoip.com", "smsdiscount.com",
	   "smslisto.com", "sparvoip.de", "voipblast.com" , "voipbuster.com", "voipbusterpro.com", "voipcheap.co.uk",
	   "voipcheap.com", "voipdiscount.com", "voipgain.com", "voipian.com", "voipraider.com",
	   "voipstunt.com", "voipwise.com", "voipzoom.com", "webcalldirect.com" }; 
	
	
	
	private static final int PICK_CONTACT = 3;
	//private static final int PICK_CONTACT_DEPRECATED = 33;
	public EditText field1;
	public TextView balance;
	public TextView provDet;
	private boolean refreshed = false;
	private boolean startup;
	protected SharedPreferences preferences;
    protected String usernameString;
    protected String passwordString;
    protected String providerString;
    protected String sourceNumberString;
    protected String destinationNumberString;
    protected String accessNumberString;
    private InputMethodManager imm = null;
    protected boolean isVisible = true;
    protected ImageButton b12;
    protected boolean callBackDebugBoolean = false;
    AccountsSQLHelper dh;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.main);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if(preferences.getBoolean("licenced", false))
        {
        	
        	checkLicense();
        }
        

        
        this.dh = new AccountsSQLHelper(dialNow.this.getApplicationContext());
        Display display = getWindowManager().getDefaultDisplay(); 
        field1 = (EditText)findViewById(R.id.EditText01);
        balance = (TextView)findViewById(R.id.TextView02);
        provDet = (TextView)findViewById(R.id.TextView01);
        
        
        ImageButton b10 = (ImageButton)findViewById(R.id.imageButton2);
        b12 = (ImageButton)findViewById(R.id.imageButton3);
        b12.getBackground().setColorFilter(0x0000FFFF, PorterDuff.Mode.MULTIPLY);
        b12.setMinimumWidth(display.getWidth()/3);

        ImageButton b13 = (ImageButton)findViewById(R.id.imageButton1);
        //ImageButton b01 = (ImageButton)findViewById(R.id.Button01);
        //TableLayout table1 = (TableLayout)findViewById(R.id.TableLayout01);
        b10.getBackground().setColorFilter(0x0000FFFF, PorterDuff.Mode.MULTIPLY);
        b13.getBackground().setColorFilter(0x0000FFFF, PorterDuff.Mode.MULTIPLY);
        b10.setMinimumWidth(display.getWidth()/3);
        b13.setMinimumWidth(display.getWidth()/3);
        
       
        b10.setMaxWidth(display.getWidth()/3);
        //b10.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);//verde
        //b11.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);//rosu
        //b12.setWidth(display.getWidth()/3);
       
        //b10.setText("Call");
        //b12.setText("KeyPad");
        //b01.setText("CallBack");
        field1.setHint("Enter # Here");
        
        startup = preferences.getBoolean("refreshOnStartup", false);
        balance.setText("" + this.dh.getCount());
        if(startup == true && refreshed == false)
        {
        	
        	//new getContents().execute("");
        	refreshed = true;
        	
        }
        
        
        
        final TextView x = (TextView)findViewById(R.id.country);
        field1.setInputType(InputType.TYPE_CLASS_PHONE);
        imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(field1, 1);
        balance.setOnClickListener(new OnClickListener() 
        {
        	
        	

			public void onClick(View v) {
				
				
				//refreshAccounts();

				
				
				
			}
        	
        	
        });
        
        getData();
        
        
        field1.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				
				
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
				
				
				x.setText(CountryCodes.searchFor(field1.getText().toString()));
				if(x.getText().toString().equalsIgnoreCase("Invalid Number")){
					x.setVisibility(0);
					
				if(field1.getText().toString().startsWith("00")){
					
					field1.setText("+" + field1.getText().toString().substring(2));
				//TO DO !!!	
					
				}
				}
				
				
				
			}
        	
        	
        	
        });
        
        if(preferences.getBoolean("autoFetchOwnNumber", true) == true)
        {
        	
        	TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
            
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("ownNumber", tMgr.getLine1Number());
            editor.commit();
        	
        }
        
       
        b10.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {  // onClick Method
            	final CharSequence[] items = {"CallBack", "Call"};

            	AlertDialog.Builder builder = new AlertDialog.Builder(dialNow.this);
            	builder.setTitle("Choose An Action ...");
            	builder.setItems(items, new DialogInterface.OnClickListener() {
            	    public void onClick(DialogInterface dialog, int item) {
            	        if(item == 1){
            	        	
            	        	String phone = field1.getText().toString();
                        	String prefix = preferences.getString("defaultPrefix", "");
                        	if(!phone.startsWith("+") && !phone.startsWith("00") && prefix.length() > 0)
                        		phone = prefix + phone;
                        	
                        	if(phone == "")
                        	{
                        		
                        		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
                        		
                        	}
                        	else if(!phone.startsWith("+") && !phone.startsWith("00"))
                        	{
                        		
                        		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
                        		
                        	}
                        	else
                        	{
                        	Intent i = new Intent(dialNow.this, CallHandler.class);
                        	i.putExtra("number", phone);
                        	i.putExtra("choice", 1);
                        	i.putExtra("country", CountryCodes.searchFor(phone));
                        	dialNow.this.startActivity(i);
                        	
                      	    dialNow.this.finish();
                        	}
            	        	
            	        }
            	        else if(item == 0){
            	        	
            	        	String phone = field1.getText().toString();
                        	sourceNumberString = preferences.getString("ownNumber","");
                        	String prefix = preferences.getString("defaultPrefix", "");
                        	if(!phone.startsWith("+") && !phone.startsWith("00") && prefix.length() > 0)
                        		phone = prefix + phone;

                        	
                        	if(phone == "")
                        	{
                        		
                        		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
                        		
                        	}
                        	else if(!phone.startsWith("+") && !phone.startsWith("00"))
                        	{
                        		
                        		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
                        		
                        	}
                        	else if(!sourceNumberString.startsWith("+"))
                			{
                				
                				Toast.makeText(getApplicationContext(), "Unable to make CallBack. Please update your own number in International format", Toast.LENGTH_LONG).show();
                				Intent i = new Intent(dialNow.this, dialNowPrefs.class);
                    			startActivityForResult(i, 103);
                			}
                        	else
                        	{
                        	
                        		String sourceNumberString = preferences.getString("ownNumber","");
                            	if(sourceNumberString.startsWith("+"))
                            	{
                            	String sourceNumberCountry = CountryCodes.searchFor(sourceNumberString);
                            	Intent i = new Intent(dialNow.this, CallHandler.class);
                             	i.putExtra("number", phone);
                             	i.putExtra("choice", 2);
                             	i.putExtra("country", CountryCodes.searchFor(phone));
                             	i.putExtra("sCountry", sourceNumberCountry);
                             	i.putExtra("sNumber", sourceNumberString);
                             	dialNow.this.startActivity(i);
                             	
                           	    dialNow.this.finish();
                            	}	
                        	
                        	}
            	        	
            	        }
            	        
            	    }
            	});
            	AlertDialog alert = builder.create();
            	alert.show();
            	
            	}
            });
        
        b12.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {  // onClick Method
            	 field1.setInputType(InputType.TYPE_CLASS_PHONE);
            	 if(isVisible == true)
            	 {
        		
            	 imm.hideSoftInputFromWindow(field1.getWindowToken(), 0);
            	 isVisible = false;
            	 //b12.setText("Show KeyPad");
            	 }
            	 else
            	 {
            		 
                	 imm.showSoftInput(field1, 1);
                	 isVisible = true;
                	 //b12.setText("Hide KeyPad");
            	 }
            }});
        
        b13.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {  // onClick Method
            	 /*//Intent myIntent = new Intent(v.getContext(), ContactList.class);
                 //startActivityForResult(myIntent, 0);
            	int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
                	if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
                		Intent intent = new Intent(dialNow.this, ContactListerLegacy.class);
                   	  	imm.hideSoftInputFromWindow(field1.getWindowToken(), 0);
                        startActivityForResult(intent, PICK_CONTACT);
                	}
                	else{
            	Intent intent = new Intent(dialNow.this, ContactLister.class);
           	  	imm.hideSoftInputFromWindow(field1.getWindowToken(), 0);
                startActivityForResult(intent, PICK_CONTACT);
                	}*/
            	
            	dialNow.this.startActivityForResult(ContactsWrapper.getInstance().getPickPhoneIntent(), PICK_CONTACT);
            	
            }});
        
        b13.setOnLongClickListener(new OnLongClickListener(){

			public boolean onLongClick(View v) {
					clear();
					
				return true;
			}
        }
        );
        
        
        
        
        /*b01.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {  // onClick Method
            	
            	String phone = field1.getText().toString();
            	
            	if(phone == "")
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
            		
            	}
            	else if(!phone.startsWith("+") && !phone.startsWith("00"))
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
            		
            	}
            	else
            	{
            	
            		new callBack().execute("");	
            	
            	}
            }});*/
        
        
        try {
            //current version
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int versionCode = packageInfo.versionCode; 

            //version where changelog has been viewed
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
            int viewedChangelogVersion = settings.getInt("changeLogVersion", 0);

            if(viewedChangelogVersion<versionCode) {
                Editor editor=settings.edit();
                editor.putInt("changeLogVersion", versionCode);
                editor.commit();
                displayChangeLog();
            }
        } catch (NameNotFoundException e) {
            Log.w("Unable to get version code. Will not show changelog", e);
        }
        
        
    }
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data){
        super.onActivityResult(reqCode, resultCode, data);
     
        switch(reqCode){
           case (PICK_CONTACT):
             if (resultCode == Activity.RESULT_OK){
            	 final String phone = ContactsWrapper.getInstance().getNumber
					(this.getContentResolver(), data.getData());
                     field1.setText(phone);
                     field1.setSelection(phone.length());
                     
             
          
             }
           break;

        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
   
    @Override 
    protected void onDestroy() {
          super.onDestroy();
          this.dh.stop();
          
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// We have only one menu option
		case R.id.preferences:
			// Launch Preference activity
			Intent i = new Intent(dialNow.this, dialNowPrefs.class);
			startActivityForResult(i, 103);
			break;
		case R.id.about01:
			Intent e = new Intent(dialNow.this, AboutUs.class);
			startActivity(e);
			break;
		case R.id.accounts:
			Intent x = new Intent(dialNow.this, AccountManager.class);
			startActivity(x);
			break;
		case R.id.rules:
			Intent u = new Intent(dialNow.this, RulesManager.class);
			startActivity(u);
			break;
		case R.id.support:
			support();
			break;
		case R.id.twitter:
			twitter();
			break;

		}
		return true;
	}

    
    private void clear()
    {
    	
    	field1.setText("");
    	
    }
    
    
    
    
    
    /*public class callBack extends AsyncTask<String, Void, String> {
    	final ProgressDialog progress = ProgressDialog.show(dialNow.this,    
                "Requesting CallBack ... ", "Please wait ... You will receive a Private Call after this dialog closes.", true);
    	
    	
    	@Override
    	protected String doInBackground(String... params) {
    		try{
        		
        		
				usernameString = preferences.getString("username", "none");
				passwordString = preferences.getString("psswd", "none");
				providerString = preferences.getString("betamaxProvider", "0");
				sourceNumberString = preferences.getString("ownNumber", "");
				String number = field1.getText().toString();
				callBackDebugBoolean = preferences.getBoolean("callbackDebug", false);
				
				if(number.startsWith("+"))
				{
					
					number = number.replace('+', '0');
					number = "0" + number;
					
				}
		
				if(sourceNumberString.startsWith("+"))
				{
					
					sourceNumberString = sourceNumberString.replace('+', '0');
					sourceNumberString = "0" + sourceNumberString;
					
				}
				
				if(sourceNumberString.equalsIgnoreCase(""))
				{
					TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
					sourceNumberString= tMgr.getLine1Number();
					
				}
				
				//Log.e("providerString", providerString);
				String actualProvider = PROVIDERS[new Integer(Integer.parseInt(providerString))];
				//Log.e("actualProvider", actualProvider);
				if(!providerString.equalsIgnoreCase("0"))
				{
			    HttpClient httpclient = new DefaultHttpClient();  
		        HttpGet httpget = new HttpGet("http://www.aldeaglobal.net/callserver/call.php?provider="+actualProvider+"&us="+usernameString.trim()+"&ps="+passwordString.trim()+"&tela="+sourceNumberString+"&telb="+number);
		       
	            // Add your data  
	            
	      
	            // Execute HTTP Post Request  
	            HttpResponse response = httpclient.execute(httpget);  
	            
	            byte buffer[] = new byte[1024] ;
				InputStream is = response.getEntity().getContent() ;
				int numBytes = is.read(buffer) ;
				is.close();
				
				 String entityContents = new String(buffer,0,numBytes) ;
			    
					

					
		            
				 return entityContents;   
				}
				
				
				return "none";
		            
		           
		            
	            
	            
	            
	            
	              
	        } catch (ClientProtocolException e) {  
	        	
	        	return e.getMessage();
	        } catch (IOException e) {  
	        	
	        	return e.getMessage();
	        	
	        }
	        
	       
    	}

    	
    	@Override
    	protected void onPostExecute(String result) {
    		
    		
            progress.dismiss();
            
            if(callBackDebugBoolean == true)
            	displayDebug(result);
        	 
    		
    		super.onPostExecute(result);
    	}

    	
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    	}

    	
    	@Override
    	protected void onProgressUpdate(Void... values) {
    		// TODO Auto-generated method stub
    		super.onProgressUpdate(values);
    	}

    }
    */
    public void displayChangeLog()
    {
    	
    	
    	LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.changelog_view, null);
        TextView thankyou = (TextView)view.findViewById(R.id.thankyou);
        thankyou.setText(Html.fromHtml("Thank you for your support.To benefit from the full functionality of this app please make it the default " +
        				 "dialer. <br> Special thanks to <a href='market://search?q=pub:\"Felix Bechstein\"'>Felix Bechstein</a>"));
        new AlertDialog.Builder(this)
        .setTitle("Changelog")
        .setView(view)
        .setNegativeButton("Close", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
              dialog.dismiss();
          }
        })
        .show();
    }
    
    /*public void displayDebug(final String message)
    {
    	ComponentName comp = new ComponentName(dialNow.this, dialNow.class);
        PackageInfo pinfo = null;
		try {
			pinfo = dialNow.this.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	final String firmwareVersion = Build.VERSION.RELEASE;
    	final String model = Build.MODEL;
    	final String display = Build.DISPLAY;
    	final String appVersion = pinfo.versionName;
    	final int appCode = pinfo.versionCode;
    	providerString = preferences.getString("betamaxProvider", "0");
    	final String actualProvider = PROVIDERS[new Integer(Integer.parseInt(providerString))];
    	
    	
    	
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Debug Dialog")
    	       .setMessage("Firmware : " + firmwareVersion + "\n" +
    	    		   	   "Phone Model : " + model + "\n" +
    	    		   	   "ROM : " + display + "\n" +
    	    		   	   "App Version : " + appVersion + "\n" +
    	    		   	   "App Code : " + appCode + "\n" +
    	    		   	   "BetaMax Provider : " + actualProvider + "\n\n\n" + 
    	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
    	    		   	   "-------------------------------------------\n" + 
    	    		   	   message+
    	    		   	   "\n-------------------------------------------")
    	       .setCancelable(false)
    	       .setNegativeButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       })
    	       .setPositiveButton("Send To Dev", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                       
                       emailIntent.setType("plain/text");
                  
                       emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "support@boxedinsoftware.com"});
                
                       emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[DEBUG BetaMax Dialer Pro v" + appVersion +"]");
                
                       emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
                    		   "\n\n\n-------------------------------------------\n" +
                       		   "Firmware : " + firmwareVersion + "\n" +
        	    		   	   "Phone Model : " + model + "\n" +
        	    		   	   "ROM : " + display + "\n" +
        	    		   	   "App Version : " + appVersion + "\n" +
        	    		   	   "App Code : " + appCode + "\n" + 
        	    		   	   "BetaMax Provider : " + actualProvider + "\n\n\n" +
        	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
        	    		   	   "-------------------------------------------\n" + 
        	    		   	   message+
        	    		   	   "\n-------------------------------------------");
        
                       dialNow.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.show();
        
        
        
    }*/
    
    
    public void getData()
    {
    	
    	try
    	{
    		field1.setText(this.getIntent().getDataString());
    	}
    	catch(Exception e)
    	{
    		
    	}
    	
    	
    	
    }
    
    
    public void support(){
    	
    	ComponentName comp = new ComponentName(dialNow.this, dialNow.class);
        PackageInfo pinfo = null;
		try {
			pinfo = dialNow.this.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		final String appVersion = pinfo.versionName;
    	
    	final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        
        emailIntent.setType("plain/text");
   
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "support@boxedinsoftware.com"});
 
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[Support BetaMax Dialer Pro v" + appVersion +"]");

        dialNow.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    	
    }
    
   public void twitter(){
	   
	   Intent twitterIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://mobile.twitter.com/#!/BMAXDialerPro")); 
	   startActivity(twitterIntent); 
	   
   }
    
    
}